package net.zjitc.controller;

import net.zjitc.pojo.CategorySecond;
import net.zjitc.pojo.Product;
import net.zjitc.service.CategorySecondService;
import net.zjitc.service.Impl.CategorySecondServiceImpl;
import net.zjitc.service.Impl.ProductServiceImpl;
import net.zjitc.service.ProductService;
import net.zjitc.utils.CommonUtils;
import net.zjitc.utils.PageBean;
import net.zjitc.utils.dispacher.URLMapping;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.InputStream;
import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2017/11/22.
 */
public class AdminProductController {
    ProductService productService =new ProductServiceImpl();
    CategorySecondService secondService=new CategorySecondServiceImpl();
    @URLMapping(url = "/findAllProduct")
    public String findAllProduct(HttpServletRequest request, HttpServletResponse response)
    {
        //通过参数传页码
        String pageNumber=request.getParameter("page");
        int page=Integer.valueOf(pageNumber);

        int pageSize=12;
        PageBean<Product> pageBean=productService.findPageBean(page,pageSize);
        request.setAttribute("pageBean",pageBean);
        return "/admin/product/list.jsp";
    }

    @URLMapping(url = "/productAddUI")
    public String productAddUI(HttpServletRequest request, HttpServletResponse response)
    {
        //准备二级分类的回显数据
        List<CategorySecond> list=secondService.findAllCategorySecond();
        request.setAttribute("list",list);
        return "/admin/product/add.jsp";
    }


    @URLMapping(url = "/productAdd")
    public String productAdd(HttpServletRequest request, HttpServletResponse response)
    {
        //创建一个工厂
        DiskFileItemFactory factory=new DiskFileItemFactory();
        //解析器
        ServletFileUpload fileUpload=new ServletFileUpload(factory);
        fileUpload.setHeaderEncoding("UTF-8");
        //解析
        Product product=new Product();
        CategorySecond categorySecond=new CategorySecond();
        try {
            List<FileItem> fileItems=fileUpload.parseRequest(request);
            for (FileItem item:fileItems){
                //处理表单普通数据项
                if(item.isFormField()){
                    if("pname".equals(item.getFieldName())){
                            product.setPname(item.getString("utf-8"));
                    }
                    if("shopPrice".equals(item.getFieldName())){
                        product.setShop_price(Double.valueOf(item.getString()));
                    }
                    if("marketPrice".equals(item.getFieldName())){
                        product.setMarket_price(Double.valueOf(item.getString()));
                    }
                    if("isHot".equals(item.getFieldName())){
                        product.setIs_hot(Integer.valueOf(item.getString()));
                    }
                    if("pdesc".equals(item.getFieldName())){
                        product.setPdesc(item.getString("utf-8"));
                    }
                    if("csid".equals(item.getFieldName())){
                        categorySecond.setCsid(Integer.valueOf(item.getString()));
                        product.setCategorySecond(categorySecond);
                    }
                }else{//处理文件
                    //文件输入流 文件名可能一样    products/5
                    String fileName = item.getName();

                    fileName= CommonUtils.getUUID()+fileName;

                    InputStream inputStream=item.getInputStream();
                    //输入流文件保存到本地(图片的实际位置)
                    String path=request.getServletContext().getRealPath("/products/5");
                    File dir=new File(path);
                    if(!dir.exists()){
                        dir.mkdirs();
                    }
                    File file=new File(dir,fileName);
                    item.write(file);
                    //保存到数据库中的路径
                    String imgPath ="products/5/"+fileName;
                    product.setImage(imgPath);
                }
            }
            product.setPdate(new Date());

        } catch (Exception e) {
            e.printStackTrace();
        }
        //将product添加到数据库
        productService.productAdd(product);
        String url = request.getContextPath()+"/findAllProduct?page=1";
        return "Redirect:"+url ;
    }

    @URLMapping(url = "/productEditUI")
    public String productEditUI(HttpServletRequest request, HttpServletResponse response)
    {
        String pid=request.getParameter("pid");
        Product product=productService.findProductById(pid);
        request.setAttribute("p",product);
        List<CategorySecond> list=secondService.findAllCategorySecond();
        request.setAttribute("list",list);

        return "/admin/product/edit.jsp";
    }
    @URLMapping(url = "/productEdit")
    public String productEdit(HttpServletRequest request, HttpServletResponse response)
    {

        DiskFileItemFactory factory=new DiskFileItemFactory();

        ServletFileUpload fileUpload=new ServletFileUpload(factory);
        fileUpload.setHeaderEncoding("UTF-8");

        Product product=new Product();
        CategorySecond categorySecond=new CategorySecond();
        try {
            List<FileItem> fileItems=fileUpload.parseRequest(request);
            for (FileItem item:fileItems){
                if(item.isFormField()){
                    if("pid".equals((item.getFieldName()))){
                        product.setPid(Integer.valueOf(item.getString()));
                    }
                    if("pname".equals(item.getFieldName())){
                        product.setPname(item.getString("utf-8"));
                    }
                    if("shopPrice".equals(item.getFieldName())){
                        product.setShop_price(Double.valueOf(item.getString()));
                    }
                    if("marketPrice".equals(item.getFieldName())){
                        product.setMarket_price(Double.valueOf(item.getString()));
                    }
                    if("isHot".equals(item.getFieldName())){
                        product.setIs_hot(Integer.valueOf(item.getString()));
                    }
                    if("pdesc".equals(item.getFieldName())){
                        product.setPdesc(item.getString("utf-8"));
                    }
                    if("csid".equals(item.getFieldName())){
                        categorySecond.setCsid(Integer.valueOf(item.getString()));
                        product.setCategorySecond(categorySecond);
                    }

                }else{
                        String fileName = item.getName();

                        fileName= CommonUtils.getUUID()+fileName;

                        InputStream inputStream=item.getInputStream();

                        String path=request.getServletContext().getRealPath("/products/5");
                        File dir=new File(path);
                        if(!dir.exists()){
                            dir.mkdirs();
                        }
                        File file=new File(dir,fileName);
                        item.write(file);

                        String imgPath ="products/5/"+fileName;
                        product.setImage(imgPath);
                }
            }
            product.setPdate(new Date());

        } catch (Exception e) {
            e.printStackTrace();
        }

        productService.productEdit(product);
        String url = request.getContextPath()+"/findAllProduct?page=1";
        return "Redirect:"+url ;
    }

    @URLMapping(url = "/productDelete")
    public String productDelete(HttpServletRequest request, HttpServletResponse response)
    {
        String pid=request.getParameter("pid");
        productService.productDelete(pid);
        String url = request.getContextPath()+"/findAllProduct?page=1";
        return "Redirect:"+url ;
    }
}
